import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Space,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Typography,
  theme,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useMessage } from '../contexts/MessageContext';
import { sampleAPI } from '../services/api';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

const SampleManagement = () => {
  const { t } = useTranslation();
  const { token } = theme.useToken();
  const { messageApi } = useMessage();
  const [samples, setSamples] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingSample, setEditingSample] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState({});
  const [nextRefreshTime, setNextRefreshTime] = useState(null);

  // 获取样地列表（使用当前状态中的搜索参数）
  const fetchSamples = async (params = {}) => {
    setLoading(true);
    try {
      const response = await sampleAPI.getSampleList({
        code: 0, // 查询全部
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        pageOrderName: 'id',
        pageOrderBy: 'desc',
        ...searchParams, // 包含搜索参数
        ...params,
      });

      if (response && response.data) {
        setSamples(response.data.list || []);
        setPagination(prev => ({
          ...prev,
          total: response.data.totalCount || 0,
        }));
      }
    } catch (error) {
      messageApi.error(t('sample.fetchFailed'));
      console.error('获取样地列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取样地列表（直接传入搜索参数，不依赖状态）
  const fetchSamplesWithParams = async (params = {}) => {
    setLoading(true);
    try {
      const { pageNo, pageSize, ...searchParamsFromParams } = params;
      const response = await sampleAPI.getSampleList({
        code: 0, // 查询全部
        pageNo: pageNo || pagination.current,
        pageSize: pageSize || pagination.pageSize,
        pageOrderName: 'id',
        pageOrderBy: 'desc',
        ...searchParamsFromParams, // 直接使用传入的搜索参数
      });

      if (response && response.data) {
        setSamples(response.data.list || []);
        setPagination(prev => ({
          ...prev,
          current: pageNo || prev.current,
          total: response.data.totalCount || 0,
        }));
      }
    } catch (error) {
      messageApi.error(t('sample.fetchFailed'));
      console.error('获取样地列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSamples();
  }, []);

  // 自动刷新功能 - 每10分钟刷新一次
  useEffect(() => {
    // 设置下次刷新时间
    const setRefreshTime = () => {
      const nextTime = new Date();
      nextTime.setMinutes(nextTime.getMinutes() + 10);
      setNextRefreshTime(nextTime);
    };

    setRefreshTime();

    // 设置定时器，每10分钟执行一次
    const interval = setInterval(() => {
      console.log('自动刷新样地数据...');
      fetchSamples();
      setRefreshTime();
    }, 10 * 60 * 1000); // 10分钟 = 10 * 60 * 1000毫秒

    // 清理定时器
    return () => {
      clearInterval(interval);
    };
  }, []);

  // 处理表格变化
  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
    // 直接传递新的分页参数，避免异步状态更新问题
    fetchSamplesWithParams({
      pageNo: newPagination.current,
      pageSize: newPagination.pageSize,
      ...searchParams
    });
  };

  // 打开添加/编辑模态框
  const showModal = (sample = null) => {
    setEditingSample(sample);
    setModalVisible(true);
    if (sample) {
      form.setFieldsValue(sample);
    } else {
      form.resetFields();
    }
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
    setEditingSample(null);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (editingSample) {
        // 编辑
        await sampleAPI.editGhySample({
          id: editingSample.id,
          ...values,
        });
        messageApi.success(t('sample.editSuccess'));
      } else {
        // 添加
        await sampleAPI.addGhySample(values);
        messageApi.success(t('sample.addSuccess'));
      }

      handleCancel();
      fetchSamples();
    } catch (error) {
      messageApi.error(editingSample ? t('sample.editFailed') : t('sample.addFailed'));
      console.error('提交样地信息错误:', error);
    }
  };

  // 删除样地
  const handleDelete = async (ids) => {
    try {
      await sampleAPI.delGhySample(ids);
      messageApi.success(t('sample.deleteSuccess'));
      fetchSamples();
    } catch (error) {
      messageApi.error(t('sample.deleteFailed'));
      console.error('删除样地错误:', error);
    }
  };

  // 搜索功能
  const handleSearch = (values) => {
    const searchData = {};

    // 样地编号搜索（确保为整数，允许输入0）
    if (typeof values.code === 'number') {
      searchData.code = parseInt(values.code);
    }

    // 样地名称搜索（模糊搜索）
    if (values.name && values.name.trim()) {
      searchData.name = values.name.trim();
    }

    setSearchParams(searchData);
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页

    // 直接使用新的搜索参数，而不是依赖状态更新
    fetchSamplesWithParams({ pageNo: 1, ...searchData });
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 }));
    // 直接传入空的搜索参数
    fetchSamplesWithParams({ pageNo: 1 });
  };

  // 表格列定义
  const columns = [
    {
      title: t('sample.sampleCode'),
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: t('sample.sampleName'),
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      render: (value) => value || '--',
    },
    {
      title: t('sample.longitude'),
      dataIndex: 'lng',
      key: 'lng',
      width: 120,
      render: (value) => value ? value.toFixed(6) : '-',
    },
    {
      title: t('sample.latitude'),
      dataIndex: 'lat',
      key: 'lat',
      width: 120,
      render: (value) => value ? value.toFixed(6) : '-',
    },
    {
      title: t('sample.createTime'),
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (updatedAt) => {
        if (!updatedAt) return '-';
        // 处理秒级时间戳
        if (typeof updatedAt === 'number' && updatedAt.toString().length === 10) {
          return dayjs.unix(updatedAt).format('YYYY-MM-DD HH:mm:ss');
        }
        return dayjs(updatedAt).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: t('sample.operation'),
      key: 'action',
      width: 200,
      fixed: 'right', // 固定操作列到右侧
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            {t('common.edit')}
          </Button>
          <Popconfirm
            title={t('sample.deleteConfirm')}
            onConfirm={() => handleDelete(record.id)}
            okText={t('common.confirm')}
            cancelText={t('common.cancel')}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              {t('common.delete')}
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Space align="center">
            <EnvironmentOutlined style={{ fontSize: 24, color: '#1890ff' }} />
            <Title level={2} style={{ margin: 0 }}>
              {t('sample.title')}
            </Title>
          </Space>
        </Col>
        <Col>
          <Space align="center" size="large">
            {nextRefreshTime && (
              <div style={{ textAlign: 'right' }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  🔄 下次刷新: {dayjs(nextRefreshTime).format('HH:mm:ss')}
                </Text>
                <br />
                <Text type="secondary" style={{ fontSize: '11px' }}>
                  平均采集间隔: 10分钟
                </Text>
              </div>
            )}
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
              size="large"
              style={{
                borderRadius: 8,
                height: 40,
                paddingLeft: 20,
                paddingRight: 20,
              }}
            >
              {t('sample.addSample')}
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <div style={{
        marginBottom: 24,
        padding: '20px 0',
        borderBottom: '1px solid #f0f0f0'
      }}>
        <Form
          form={searchForm}
          onFinish={handleSearch}
          style={{ width: '100%' }}
        >
          <Row gutter={[24, 16]} align="bottom">
            <Col xs={24} sm={12} md={6} lg={5}>
              <Form.Item
                name="code"
                label={
                  <span style={{
                    fontSize: '14px',
                    fontWeight: 500,
                    color: token.colorText
                  }}>
                    样地编号
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <InputNumber
                  placeholder="请输入样地编号"
                  controls={false}
                  size="large"
                  min={0}
                  precision={0}
                  style={{
                    width: '100%',
                    borderRadius: 8,
                    border: '1px solid #d9d9d9',
                    transition: 'all 0.3s'
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = '#1890ff';
                    e.target.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = '#d9d9d9';
                    e.target.style.boxShadow = 'none';
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6} lg={5}>
              <Form.Item
                name="name"
                label={
                  <span style={{
                    fontSize: '14px',
                    fontWeight: 500,
                    color: token.colorText
                  }}>
                    样地名称
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <Input
                  placeholder="请输入样地名称"
                  allowClear
                  size="large"
                  style={{
                    borderRadius: 8,
                    border: '1px solid #d9d9d9',
                    transition: 'all 0.3s'
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = '#1890ff';
                    e.target.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = '#d9d9d9';
                    e.target.style.boxShadow = 'none';
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={14}>
              <Form.Item style={{ marginBottom: 0 }}>
                <Space size="middle">
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SearchOutlined />}
                    size="large"
                    style={{
                      borderRadius: 8,
                      height: 40,
                      paddingLeft: 24,
                      paddingRight: 24,
                      fontWeight: 500,
                      boxShadow: '0 2px 4px rgba(24, 144, 255, 0.3)',
                      border: 'none'
                    }}
                  >
                    搜索
                  </Button>
                  <Button
                    onClick={handleReset}
                    size="large"
                    style={{
                      borderRadius: 8,
                      height: 40,
                      paddingLeft: 24,
                      paddingRight: 24,
                      fontWeight: 500,
                      color: token.colorTextSecondary,
                      borderColor: '#d9d9d9'
                    }}
                  >
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>

      <Table
        columns={columns}
        dataSource={samples}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `${t('common.total')} ${range[0]}-${range[1]} ${t('common.items')}/${total} ${t('common.items')}`,
        }}
        onChange={handleTableChange}
        scroll={{ x: 800 }}
        style={{
          borderRadius: 8,
        }}
      />

      <Modal
        title={editingSample ? t('sample.editSample') : t('sample.addSample')}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={600}
        destroyOnHidden
        style={{
          borderRadius: 12,
        }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 0,
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('sample.sampleCode')}
                name="code"
                rules={[
                  { required: true, message: '请输入样地编号' },
                  { type: 'number', message: '样地编号必须为数字' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入样地编号"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('sample.sampleName')}
                name="name"
                rules={[{ required: true, message: '请输入样地名称' }]}
              >
                <Input placeholder="请输入样地名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('sample.longitude')}
                name="lng"
                rules={[
                  { required: true, message: '请输入经度' },
                  { type: 'number', message: '经度必须为数字' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入经度"
                  precision={6}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('sample.latitude')}
                name="lat"
                rules={[
                  { required: true, message: '请输入纬度' },
                  { type: 'number', message: '纬度必须为数字' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入纬度"
                  precision={6}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default SampleManagement;
